#!/bin/bash

# GGB Generation Conversation API 测试脚本

echo "🧪 运行 GGB Generation Conversation API 测试..."
echo ""

# 检查测试依赖
echo "🔍 检查测试依赖..."
python -c "import pytest, httpx, pytest_asyncio" 2>/dev/null
if [ $? -ne 0 ]; then
    echo "❌ 错误: 缺少测试依赖，请运行: pip install pytest pytest-asyncio httpx"
    exit 1
fi

echo "✅ 测试依赖检查通过"
echo ""

# 检查服务是否运行
echo "🔍 检查服务状态..."
curl -s http://localhost:8080/health > /dev/null
if [ $? -ne 0 ]; then
    echo "⚠️  警告: 服务未运行，请先启动服务:"
    echo "   ./start_conversation_service.sh"
    echo ""
    echo "🚀 尝试启动服务进行测试..."
    python introduction_files/conversation_app.py &
    SERVER_PID=$!
    echo "📝 服务进程 ID: $SERVER_PID"
    
    # 等待服务启动
    echo "⏳ 等待服务启动..."
    sleep 5
    
    # 再次检查
    curl -s http://localhost:8080/health > /dev/null
    if [ $? -ne 0 ]; then
        echo "❌ 错误: 无法启动服务"
        kill $SERVER_PID 2>/dev/null
        exit 1
    fi
    
    STARTED_SERVER=true
else
    echo "✅ 服务正在运行"
    STARTED_SERVER=false
fi

echo ""

# 运行测试
echo "🎯 运行测试套件..."
echo ""

# 运行所有测试
pytest -v test/test_chat_api.py -s

TEST_RESULT=$?

# 清理
if [ "$STARTED_SERVER" = true ]; then
    echo ""
    echo "🧹 清理测试环境..."
    kill $SERVER_PID 2>/dev/null
    echo "✅ 服务已停止"
fi

echo ""
if [ $TEST_RESULT -eq 0 ]; then
    echo "🎉 所有测试通过！"
else
    echo "❌ 测试失败，请检查错误信息"
fi

exit $TEST_RESULT 